import { useRef, useEffect, useState } from 'react'

type Value<T> = T | ((prev: T) => T)
type Callback<T> = (newState: T) => void
type ReturnValue<T> = [state: T, update: (prev: Value<T>, callback?: Callback<T>) => void]

/**
 * 带有回调的 useState hook
 * @date 2021-07-15
 * @param {any} initValue   初始值
 * @returns {any}
 */
function useCallbackState<T>(initValue: T): ReturnValue<typeof initValue> {
    const [state, setState] = useState<T>(initValue)
    const calbackRef = useRef<(state: T) => void>()

    // 缓存起来
    const updateState = (value: any, callback?: (state: T) => void) => {
        setState((prev: T) => {
            calbackRef.current = callback
            return typeof value === 'function' ? value(prev) : value
        })
    }

    useEffect(() => {
        calbackRef.current && calbackRef.current(state)
    }, [state])

    return [state, updateState]
}

export default useCallbackState
